package com.regret.medicine;

import cn.hutool.core.util.NumberUtil;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import jfxtras.scene.control.LocalDateTimeTextField;

import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

public class AnalyzeController {

    @FXML
    private TextField ipField;
    @FXML
    private TextField portField;
    @FXML
    private TextField usernameField;
    @FXML
    private TextField passwordField;

    @FXML
    private Button analyzeBtn;
    @FXML
    private TextField databaseNameField;
    @FXML
    private TextField tableNameField;
    @FXML
    private TextField binPathField;
    @FXML
    private LocalDateTimeTextField startTimeField;
    @FXML
    private LocalDateTimeTextField endTimeField;
    @FXML
    private WebView webView;

    private Stage stage;

    private File file;

    Pattern pattern = Pattern.compile("([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$");

    ExecutorService executorService = Executors.newSingleThreadExecutor();


    /**
     * 解析
     */
    @FXML
    protected void onAnalyzeClicked() {

        if (checkParams()) {
            if (Objects.isNull(this.file)) {
                showText("未获取到binlog文件");
                return;
            }

            showText("开始解析文件...");

            analyzeBtn.setDisable(true);

            executorService.submit(() -> {
                analyze();
                analyzeBtn.setDisable(false);
            });

        }
    }

    public void analyze() {
        String ip = ipField.getText();
        String port = portField.getText();
        String username = usernameField.getText();
        String password = passwordField.getText();
        String databaseName = databaseNameField.getText();
        String tableName = tableNameField.getText();
        String startTime = startTimeField.getText();
        String endTime = endTimeField.getText();

        try {
            List<String> stringList = new BinlogParser(ip, port, databaseName, username, password, tableName, startTime, endTime).parse(file);
            String content = null;
            if (!stringList.isEmpty()) {
                content = "<p>" + String.join("</p><p>", stringList) + "</p>";
            } else {
                content = "<p>未解析到数据</p>";
            }
            String finalContent = content;
            Platform.runLater(() -> showText(finalContent));
            stringList.clear();
        } catch (Exception e) {
            e.printStackTrace();
            showText(e.getMessage());
        }

    }


    /**
     * 选择文件
     */
    @FXML
    protected void choiceFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择binlog文件");
        this.file = fileChooser.showOpenDialog(stage);
        if (Objects.nonNull(this.file)) {
            binPathField.setText(this.file.getAbsolutePath());
        }
    }

    /**
     * 校验参数
     */
    private boolean checkParams() {
        if (isEmpty(ipField.getText())) {
            showText("<p>数据库IP地址不能为空</p>");
            return false;
        }
        if (!pattern.matcher(ipField.getText()).matches()) {
            showText("<p>数据库IP地址格式错误</p>");
            return false;
        }
        if (isEmpty(portField.getText())) {
            showText("<p>数据库端口不能为空</p>");
            return false;
        }
        if (!NumberUtil.isNumber(portField.getText())) {
            showText("<p>数据库端口错误</p>");
            return false;
        }
        if (isEmpty(usernameField.getText())) {
            showText("<p>用户名不能为空</p>");
            return false;
        }
        if (isEmpty(passwordField.getText())) {
            showText("<p>密码不能为空</p>");
            return false;
        } else if (isEmpty(binPathField.getText())) {
            showText("<p>未选择binlog文件</p>");
            return false;
        } else {
            showText("");
            return true;
        }
    }

    private void showText(String text) {
        String html = "<html><body>" + text + "</body></html>";
        webView.getEngine().loadContent(html);
    }

    private boolean isEmpty(String str) {
        return str == null || str.length() < 1 || str.trim().length() < 1;
    }

    /**
     * 初始化
     */
    public void init(Stage stage) {
        this.stage = stage;

        this.ipField.setText("127.0.0.1");
        this.portField.setText("3306");
        this.usernameField.setText("root");
        this.passwordField.setText("123456");

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        this.startTimeField.setDateTimeFormatter(dateTimeFormatter);
        this.endTimeField.setDateTimeFormatter(dateTimeFormatter);
    }
}
